/**
 * 多语言管理工具
 */
import store from '@/store'
import { systemApi } from '@/request/system.js'

// 导入本地语言包
import zhCN from '@/locales/zh-CN.json'
import enUS from '@/locales/en-US.json'
import jaJP from '@/locales/ja-JP.json'
import ruRU from '@/locales/ru-RU.json'
import koKR from '@/locales/ko-KR.json'

// 本地语言包映射
const LOCAL_LANGUAGES = {
    'zh-CN': zhCN,
    'en-US': enUS,
    'ja-JP': jaJP,
    'ru-RU': ruRU,
    'ko-KR': koKR
}

// 支持的语言列表
export const SUPPORTED_LANGUAGES = [
    { code: 'zh-CN', name: '中文(简体)', nativeName: '中文(简体)' },
    { code: 'en-US', name: 'English', nativeName: 'English' },
    { code: 'ja-JP', name: 'Japanese', nativeName: '日本語' },
    { code: 'ru-RU', name: 'Russian', nativeName: 'Русский' },
    { code: 'ko-KR', name: 'Korean', nativeName: '한국어' }
]

export class LanguageManager {
    constructor() {
        this.languageMap = new Map()
        this.localLanguageMap = new Map()
        this.currentLanguage = 'en-US' // 默认英文
        this.defaultLanguage = 'en-US'
        this.isLoaded = false
        this.isLocalLoaded = false

        // 初始化本地语言包
        this.initializeLocalLanguages()
    }

    /**
     * 初始化本地语言包
     */
    initializeLocalLanguages() {
        try {
            // 加载所有本地语言包到Map中
            Object.keys(LOCAL_LANGUAGES).forEach(langCode => {
                const langData = LOCAL_LANGUAGES[langCode]
                const flatMap = this.flattenObject(langData)
                this.localLanguageMap.set(langCode, flatMap)
            })

            this.isLocalLoaded = true
            console.log('本地语言包初始化成功，支持语言:', Object.keys(LOCAL_LANGUAGES))
        } catch (error) {
            console.error('本地语言包初始化失败:', error)
        }
    }

    /**
     * 扁平化对象，将嵌套的键转换为点分隔的键
     * @param {Object} obj 
     * @param {string} prefix 
     * @returns {Object}
     */
    flattenObject(obj, prefix = '') {
        const flattened = {}

        for (const key in obj) {
            if (obj.hasOwnProperty(key)) {
                const newKey = prefix ? `${prefix}.${key}` : key

                if (typeof obj[key] === 'object' && obj[key] !== null && !Array.isArray(obj[key])) {
                    Object.assign(flattened, this.flattenObject(obj[key], newKey))
                } else {
                    flattened[newKey] = obj[key]
                }
            }
        }

        return flattened
    }

    /**
     * 设置当前语言
     * @param {string} languageCode 
     * @param {boolean} skipEvent - 是否跳过事件发送，防止循环调用
     */
    setCurrentLanguage(languageCode, skipEvent = false) {
        if (this.isLanguageSupported(languageCode)) {
            this.currentLanguage = languageCode
                // 保存到本地存储
            uni.setStorageSync('currentLanguage', languageCode)
                // 更新Vuex状态
            store.commit('user/SET_CURRENT_LANGUAGE', languageCode)
        } else {
            console.warn('不支持的语言代码:', languageCode)
        }
    }

    /**
     * 获取当前语言
     * @returns {string}
     */
    getCurrentLanguage() {
        // 首先尝试从本地存储获取
        // const savedLanguage = uni.getStorageSync('currentLanguage')
        // if (savedLanguage && this.isLanguageSupported(savedLanguage)) {
        //     this.currentLanguage = savedLanguage
        //     return savedLanguage
        // }

        // 如果没有保存的语言，尝试从系统语言获取
        try {
            const systemInfo = uni.getSystemInfoSync()
            const systemLanguage = systemInfo.language || 'en'

            // 映射系统语言到支持的语言
            let mappedLanguage = 'en-US' // 默认英文
            if (systemLanguage.includes('zh')) {
                mappedLanguage = 'en-US'
            } else if (systemLanguage.includes('ja')) {
                mappedLanguage = 'ja-JP'
            } else if (systemLanguage.includes('ru')) {
                mappedLanguage = 'ru-RU'
            } else if (systemLanguage.includes('ko')) {
                mappedLanguage = 'ko-KR'
            }

            this.setCurrentLanguage(mappedLanguage)
            return mappedLanguage
        } catch (error) {
            console.error('获取系统语言失败:', error)
            return this.currentLanguage
        }
    }

    /**
     * 检查是否支持指定语言
     * @param {string} languageCode 
     * @returns {boolean}
     */
    isLanguageSupported(languageCode) {
        return SUPPORTED_LANGUAGES.some(lang => lang.code === languageCode)
    }

    /**
     * 加载语言包
     */
    async loadLanguagePack() {
        try {
            const res = await systemApi.getLanguagePack()
            if (res && res.code === 200 && Array.isArray(res.data)) {
                // 将语言包数据转换为Map格式以便快速查找
                const languageMap = new Map()
                res.data.forEach(item => {
                    if (item.languageKey && item.description) {
                        languageMap.set(item.languageKey, item.description)
                    }
                })

                this.languageMap = languageMap
                this.isLoaded = true

                // 将语言包存储到store中
                store.commit('user/SET_LANGUAGE_PACK', Object.fromEntries(languageMap))

                console.log('远程语言包加载成功，共', languageMap.size, '条记录')
                return true
            }
        } catch (error) {
            console.error('加载远程语言包失败:', error)
        }
        return false
    }

    /**
     * 根据language_key获取翻译文本
     * @param {string} languageKey - 语言key
     * @param {string} fallback - 备用文本，当找不到翻译时使用
     * @param {Object} params - 插值参数
     * @returns {string} 翻译后的文本
     */
    translate(languageKey, fallback = '', params = {}) {
        if (!languageKey) {
            return fallback
        }

        let translation = fallback || languageKey

        // 优先从本地语言包获取翻译
        if (this.isLocalLoaded) {
            const currentLangMap = this.localLanguageMap.get(this.currentLanguage)

            if (currentLangMap && currentLangMap[languageKey]) {
                translation = currentLangMap[languageKey]
            } else {
                // 如果当前语言没有翻译，尝试使用默认语言
                const defaultLangMap = this.localLanguageMap.get(this.defaultLanguage)
                if (defaultLangMap && defaultLangMap[languageKey]) {
                    translation = defaultLangMap[languageKey]
                }
            }
        }

        // 如果本地语言包没有找到，尝试从远程语言包获取
        if (translation === (fallback || languageKey) && this.isLoaded) {
            const remoteTranslation = this.languageMap.get(languageKey)

            if (remoteTranslation) {
                translation = remoteTranslation
            }
        }

        // 处理插值参数
        if (params && typeof params === 'object') {
            Object.keys(params).forEach(key => {
                const regex = new RegExp(`\\{${key}\\}`, 'g')
                translation = translation.replace(regex, params[key])
            })
        }

        return translation
    }

    /**
     * 批量翻译物品列表
     * @param {Array} items - 物品列表
     * @param {string} nameField - 要翻译的名称字段，默认为'name'
     * @param {string} keyField - language_key字段名，默认为'language_key'
     * @returns {Array} 翻译后的物品列表
     */
    translateItems(items, nameField = 'name', keyField = 'language_key') {
        if (!Array.isArray(items)) {
            return items
        }

        return items.map(item => {
            if (item[keyField]) {
                const translatedName = this.translate(item[keyField], item[nameField])
                return {
                    ...item,
                    [nameField]: translatedName,
                    originalName: item[nameField] // 保留原始名称
                }
            }
            return item
        })
    }

    /**
     * 获取当前语言包大小
     */
    getLanguagePackSize() {
        let localSize = 0
        if (this.isLocalLoaded) {
            localSize = this.localLanguageMap.get(this.currentLanguage).size || 0
        }
        let remoteSize = 0
        if (this.isLoaded) {
            remoteSize = this.languageMap.size
        }
        return { local: localSize, remote: remoteSize, total: localSize + remoteSize }
    }

    /**
     * 检查是否已加载语言包
     */
    isLanguagePackLoaded() {
        return this.isLocalLoaded || this.isLoaded
    }

    /**
     * 清空语言包缓存
     */
    clearLanguagePack() {
        this.languageMap.clear()
        this.isLoaded = false
        store.commit('user/SET_LANGUAGE_PACK', {})
    }

    /**
     * 获取支持的语言列表
     */
    getSupportedLanguages() {
        return SUPPORTED_LANGUAGES
    }
}

// 创建全局实例
export const languageManager = new LanguageManager()

/**
 * 全局翻译函数
 * @param {string} languageKey - 语言key  
 * @param {string} fallback - 备用文本
 * @param {Object} params - 插值参数
 * @returns {string} 翻译后的文本
 */
export function $t(languageKey, fallback = '', params = {}) {
    return languageManager.translate(languageKey, fallback, params)
}

/**
 * Vue插件安装函数
 */
export function install(Vue) {
    // Vue 2 插件安装方式
    if (Vue.version && Vue.version.startsWith('2')) {
        // Vue 2
        Vue.prototype.$t = $t
        Vue.prototype.$language = languageManager
    } else {
        // Vue 3
        Vue.config.globalProperties.$t = $t
        Vue.config.globalProperties.$language = languageManager

        // 提供全局属性
        Vue.provide('$t', $t)
        Vue.provide('$language', languageManager)
    }
}

export default {
    install,
    LanguageManager,
    languageManager,
    $t,
    SUPPORTED_LANGUAGES
}